'''
Created on Nov 26, 2010

@author: Polido
'''

introSequence = [8, 13, 21, 34]

class SerialReader(object):
    '''
    classdocs
    '''


    def __init__(self, octorotor):
        '''
        Constructor
        '''
        self.octorotor = octorotor
        self.dataBuffer = []
    
    def appendData(self, data):
        
        for byte in list(data):
            self.dataBuffer.append(ord(byte))
        
        self.readData()
        
    def readData(self):
        while len(self.dataBuffer) > len(introSequence): #While there is more than the intro packet to read
             
            if self.correctIntroduction(): #Check if we have the correct intro packet
                
                package = self.dataBuffer[len(introSequence):] #The data without the intro
                packetLength = package[0]  #The length of the data
                
                if len(package) < packetLength: #There is not enough information to read the whole packet
                    return
                
                self.processPacket(package[1:packetLength]) #Send the packet to the buffer
                
                del self.dataBuffer[0:len(introSequence) + packetLength] #Delete the packet from stream
            
            else: 
                del self.dataBuffer[0] #Delete the first charcter and try again on the while loop
            
    def correctIntroduction(self):
        return introSequence == self.dataBuffer[0:len(introSequence)]
            
            
    def processPacket(self, packet):
        self.octorotor.processPacket(packet)
        
        
        
